#!/usr/bin/env python
# coding=utf-8
#
#  Created by Skiloop
#  Email: skiloop@126.com
#
from random import random

import cv2
import numpy as np

from binimg import image_binary
from utils import gif2jpg, ic_two_pass


def random_color():
    return [int(255 * random()), int(255 * random()), int(255 * random()), ]


def random_color_list(n):
    colors = []
    while len(colors) < n:
        color = random_color()
        if color not in colors:
            colors.append(color)
    return colors


def dejob51(ifs):
    img = cv2.imread(ifs)
    cv2.imshow('Original', img)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cv2.imshow('Gray', gray)
    blur = cv2.GaussianBlur(gray, (3, 3), 0)
    cv2.imwrite('blur.jpg', blur)
    cv2.imshow('Blur', blur)
    binary = image_binary(gray, None, 127, 255)
    cv2.imshow('Binary', binary)
    x, y = binary.shape
    cv2.imwrite('binary.jpg', binary)
    for i in range(0, x):
        for j in range(0, y):
            binary[i, j] = 0 if binary[i, j] > 254 else 1
    labelImg, ls, lm = ic_two_pass(binary)
    print len(ls)
    print ls
    limg = np.empty((x, y, 3), dtype=np.uint8)
    for i in range(0, x):
        for j in range(0, y):
            limg[i, j, :] = [255, 255, 255]
    colors = random_color_list(len(ls))
    for i, j, c in lm:
        if isinstance(i, tuple) or isinstance(j, tuple) or isinstance(c, tuple):
            pass
        color = colors[c]
        if isinstance(color, tuple):
            pass
        limg[i, j, :] = color
    cv2.imshow('labelimg', limg)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


if __name__ == '__main__':
    gif2jpg('51job/51j2.gif', 'job51.jpg')
    dejob51('job51.jpg')
